package com.util;

import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

public class ValidatorUtils {
    public static boolean handleBindingResult(BindingResult bindingResult, Model model){
        boolean hasErrors = bindingResult.hasErrors();
        if(hasErrors) {
            bindingResult.getAllErrors().forEach(objectError -> {
                if (objectError instanceof FieldError) {
                    FieldError fieldError = ((FieldError) objectError);
                    model.addAttribute(fieldError.getField(), fieldError.getDefaultMessage());
                    System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
                } else {
                    model.addAttribute(objectError.getObjectName(), objectError.getDefaultMessage());
                    System.out.println(objectError.getObjectName() + ":" + objectError.getDefaultMessage());
                }
            });
        }
        return hasErrors;
    }
}
